class Solution {
public:
    int sr, sc, endx, endy, n, m;
    int dx[4] = {0, 0, -1, 1}; // 方向数组：右、左、上、下
    int dy[4] = {1, -1, 0, 0};
    int dist[15][15] = {0}; // 记录到每个位置的最短距离
    int cnt[15][15] = {0}; // 记录到每个位置的最短路径数量
    int countPath(vector<vector<int> >& CityMap, int _n, int _m) {
        // write code here
        n = _n, m = _m;
        for(int i = 0; i < n; ++i)
        {
            for(int j = 0; j < m; ++j)
            {
                if(CityMap[i][j] == 1)
                    sr = i, sc = j;
                else if(CityMap[i][j] == 2)
                    endx = i, endy = j;
            }
        }
        return bfs(CityMap);
    }
    
    int bfs(vector<vector<int> >& CityMap)
    {
        memset(dist, -1, sizeof(dist));
        dist[sr][sc] = 0;
        cnt[sr][sc] = 1;
        queue<pair<int, int>> q;
        q.push({sr, sc});

        while(!q.empty())
        {
            auto [a, b] = q.front();
            q.pop();
            for(int i = 0; i < 4; ++i)
            {
                int x = a + dx[i], y = b + dy[i];
                if(x >= 0 && x < n && y >= 0 && y < m && CityMap[x][y] != -1)
                {
                    if(dist[x][y] == -1) // 第⼀次到这个位置
                    {
                        dist[x][y] = dist[a][b] + 1;
                        cnt[x][y] += cnt[a][b];
                        q.push({x, y});
                    }
                    else if(dist[x][y] == dist[a][b] + 1)// 已访问但距离相同（即也是最短路）
                    {
                        cnt[x][y] += cnt[a][b]; // 累加路径数
                    }
                }
            }
        }
        return cnt[endx][endy];
    }
};
//题目连接https://www.nowcoder.com/practice/491828fc7d93459db450b344c2aaaeef?tpId=128&tqId=33770&ru=/exam/oj